﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace TViewCore
{
    public class Dep
    {
        /// <summary>
        /// 全局变量，用户将指定属性的订阅者放入通知列表
        /// </summary>
        public static IWatcher Target = null;
        public static Dictionary<object,Dictionary<string, List<IWatcher>>> dicWatcher = null;
        
        static Dep()
        {
            dicWatcher = new Dictionary<object, Dictionary<string, List<IWatcher>>>();
        }
        /// <summary>
        /// 添加订阅者
        /// </summary>
        /// <param name="watcher"></param>
        public static void PushWatcher(object obj,string propertyName,IWatcher watcher)
        {
            Dictionary<string, List<IWatcher>> dicProWatchers = null;
            if (dicWatcher.ContainsKey(obj))
            {
                dicProWatchers = dicWatcher[obj];
            }
            List<IWatcher> watchers = null;
            if (dicProWatchers == null)
            {
                dicProWatchers = new Dictionary<string, List<IWatcher>>();
                dicWatcher.Add(obj, dicProWatchers);
                
            }
            if (dicProWatchers.ContainsKey(propertyName))
            {
                watchers = dicProWatchers[propertyName];
            }
            if (watchers == null)
            {
                watchers = new List<IWatcher>();
                dicProWatchers.Add(propertyName, watchers);
            }
            watchers.Add(watcher);
        }
        /// <summary>
        /// 通知
        /// </summary>
        public static void Notify(object obj,string propertyName)
        {
            if(dicWatcher.ContainsKey(obj))
            {
                var dicProWatchers = dicWatcher[obj];
                if(dicProWatchers!=null)
                {
                    if (dicProWatchers.ContainsKey(propertyName))
                    {
                        var watchers = dicProWatchers[propertyName];
                        if (watchers != null)
                        {
                            watchers.ForEach(watcher =>
                            {
                                try
                                {
                                    watcher.Update();
                                }
                                catch (Exception)
                                {
                                    //
                                }
                            });
                        }
                    }
                }
            }
            
        }
    }

}
